//
//  ViewController.m
//  tableview
//
//  Created by mac on 14-9-8.
//  Copyright (c) 2015年 党倬宇. All rights reserved.
//

#import "ViewController.h"
#import "LTableViewCell.h"
@interface ViewController ()<UITableViewDataSource,UITableViewDelegate>{
    UITableView *table;
    NSMutableArray *contacts;
    UIButton *button;
//    NSMutableArray *pricearr;
    
    NSMutableArray * Count_arr;//用来保存每次加减的变化数量
    NSMutableArray * arrprice;//总价
    NSMutableArray *arrdanjia;//单价

}
@end
 
@implementation ViewController

- (void)viewDidLoad{
    [super viewDidLoad];
    contacts = [NSMutableArray array];
    arrprice = [NSMutableArray array];
    arrdanjia = [NSMutableArray array];
    //数据元
    arr = [NSArray arrayWithObjects:@"111",@"222",@"333",@"444",@"555", nil];
    
    Count_arr = [[NSMutableArray alloc] initWithCapacity:1];
    for (int i=0; i<arr.count; i++) {

        [Count_arr addObject:[NSNumber numberWithInt:1]];
    }
    NSLog(@"1======%@",Count_arr);
    for (int i = 0; i<arr.count; i++) {
        str2 = 10+i;//单价
        [arrprice addObject:[NSNumber numberWithInt:str2]];
        [arrdanjia addObject:[NSNumber numberWithInt:str2]];
    }
        NSLog(@"2======%@",arrdanjia);
//    str1 = 1;//数量
//    str2 = 10;//单价
    
	// Do any additional setup after loading the view, typically from a nib.
    table = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, 320, 500) style:UITableViewStylePlain];
    table.delegate = self;
    table.dataSource = self;
    [self.view addSubview:table];
    for (int i = 0; i <arr.count; i++) {
        NSMutableDictionary *dic = [NSMutableDictionary dictionary];
        [dic setValue:@"NO" forKey:@"checked"];
        [contacts addObject:dic];
    }
    button = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    [button setTitle:@"全选" forState:UIControlStateNormal];
    button.frame = CGRectMake(10, 10, 100, 50);
    [button addTarget:self action:@selector(allSelect:) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:button];
    
    self.allprice = [[UILabel alloc]initWithFrame:CGRectMake(150, 10, 100, 30)];
    self.allprice.textColor = [UIColor redColor];
    [self.view addSubview:self.allprice];
    
    
}

- (void)allSelect:(UIButton*)sender{
    NSArray *anArrayOfIndexPath = [NSArray arrayWithArray:[table indexPathsForVisibleRows]];
    for (int i = 0; i < [anArrayOfIndexPath count]; i++) {
        NSIndexPath *indexPath= [anArrayOfIndexPath objectAtIndex:i];
        LTableViewCell *cell = (LTableViewCell*)[table cellForRowAtIndexPath:indexPath];
        NSUInteger row = [indexPath row];
//        for (int i = 0; i<arrprice.count; i++) {
//            [arrprice objectAtIndex:i];
//            
//            
//        }
//        NSLog(@"====%@", +[arrprice objectAtIndex:row]+)
        sum = 0;
        for (NSString * str in arrprice) {
            sum += [str intValue];
        }
//        NSLog(@"====%d",sum);
        NSString *sums= [NSString stringWithFormat:@"%d",sum];
        self.allprice.text = sums;
        NSLog(@"%lu",(unsigned long)row);
        NSMutableDictionary *dic = [contacts objectAtIndex:row];
        if ([[[(UIButton*)sender titleLabel] text] isEqualToString:@"全选"]) {
            [dic setObject:@"YES" forKey:@"checked"];
            [cell setChecked:YES];
        }else {
            [dic setObject:@"NO" forKey:@"checked"];
            [cell setChecked:NO];
        }
    }
    if ([[[(UIButton*)sender titleLabel] text] isEqualToString:@"全选"]){
        for (NSDictionary *dic in contacts) {
            [dic setValue:@"YES" forKey:@"checked"];
        }
         [(UIButton*)sender setTitle:@"取消" forState:UIControlStateNormal];
    }else{
        for (NSDictionary *dic in contacts) {
            [dic setValue:@"NO" forKey:@"checked"];
        }
        [(UIButton*)sender setTitle:@"全选" forState:UIControlStateNormal];
    }
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return arr.count;
}
//设置单元格行高
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPat{
    return 120;
}

-(NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath{
    return  @"删除";
}

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}
//设置进入编辑状态时，Cell不会缩进
- (BOOL)tableView: (UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath{
    return YES;
}

//这个方法根据参数editingStyle是UITableViewCellEditingStyleDelete执行删除
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        NSLog(@"=====%ld",(long)indexPath.row);
    }
}
/*设置标题头的宽度*/
-(CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}
#pragma mark -----返回每组头标题名称 ------
-(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    //NSLog(@"生成组（组%i）名称",section);
    NSString *titleName= @"222";
    return [NSString stringWithFormat:@"%@",titleName];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString * identifier = @"Cell";
    LTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[LTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
    }
    
    NSUInteger row = [indexPath row];
//    NSInteger ss = row+1;
//    str3 = ss *[[arrprice objectAtIndex:row] integerValue];
    
      [cell.btn2 addTarget:self action:@selector(btn2:) forControlEvents:(UIControlEventTouchUpInside)];
       [cell.jia addTarget:self action:@selector(jia:) forControlEvents:(UIControlEventTouchUpInside)];
    
    cell.jia.tag = row;
    cell.jie.tag = row;
    
    [cell.jie addTarget:self action:@selector(jie:) forControlEvents:(UIControlEventTouchUpInside)];

    //获取数量
    NSString *shuliang = [NSString stringWithFormat:@"%ld",(long)[Count_arr[indexPath.row] intValue]];
    //数量
    cell.number.text = shuliang;
    
    NSString *danjia = [NSString stringWithFormat:@"单价:%@",[arrdanjia objectAtIndex:indexPath.row]];
    cell.price.text = danjia;
    
    //总价
    NSString *zongjia = [NSString stringWithFormat:@"总价:%@",[arrprice objectAtIndex:indexPath.row]];
    cell.accprice.text = zongjia;
    
    cell.label.text = [arr objectAtIndex:indexPath.row];
//    cell.label.text =[[array2 objectAtIndex:indexPath.row]objectForKey:@"title"];
    NSMutableDictionary *dic = [contacts objectAtIndex:row];
    if ([[dic objectForKey:@"checked"] isEqualToString:@"NO"]) {
        [dic setObject:@"NO" forKey:@"checked"];
        [cell setChecked:NO];
    }else {
        [dic setObject:@"YES" forKey:@"checked"];
        [cell setChecked:YES];
    }
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    return cell;
}


-(void)jia:(UIButton *)btn{
    NSLog(@"%ld",(long)btn.tag);
    [Count_arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx == btn.tag){
            [Count_arr replaceObjectAtIndex:idx withObject:[NSNumber numberWithInt:[Count_arr[idx] intValue]+1]];
            
            _sumNumber =[[Count_arr objectAtIndex:btn.tag]integerValue];
            
            str3 =_sumNumber *[[arrdanjia objectAtIndex:btn.tag] integerValue];
            NSString *sss = [NSString stringWithFormat:@"%ld",str3];
            [arrprice replaceObjectAtIndex:btn.tag withObject:sss];
//            NSLog(@"====%@",arrprice);
//            NSLog(@"数量===%ld",(long)_sumNumber);
            
            sum = 0;
            for (NSString * str in arrprice) {
                sum += [str intValue];
                
            }
            NSLog(@"====%d",sum);
            NSString *sums= [NSString stringWithFormat:@"%d",sum];
            self.allprice.text = sums;
            [table reloadData];
            *stop = YES;
        }
    }];
    
}
-(void)jie:(UIButton *)btn{
    NSLog(@"%ld",(long)btn.tag);
    [Count_arr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
        if (idx == btn.tag){
            [Count_arr replaceObjectAtIndex:idx withObject:[NSNumber numberWithInt:[Count_arr[idx] intValue]-1]];
           
             NSInteger sun = [[Count_arr objectAtIndex:btn.tag] integerValue];
            str3 =sun *[[arrdanjia objectAtIndex:btn.tag] integerValue];
            NSString *sss = [NSString stringWithFormat:@"%ld",str3];
            [arrprice replaceObjectAtIndex:btn.tag withObject:sss];
            sum = 0;
            for (NSString * str in arrprice) {
                sum += [str intValue];
                
            }
            NSLog(@"====%d",sum);
            NSString *sums= [NSString stringWithFormat:@"%d",sum];
            self.allprice.text = sums;
            if (sun<1) {
                               NSInteger shuliang = [[Count_arr objectAtIndex:btn.tag] integerValue]+1;
                str3 =shuliang *[[arrdanjia objectAtIndex:btn.tag] integerValue];
                NSString *sss = [NSString stringWithFormat:@"%ld",str3];
                [arrprice replaceObjectAtIndex:btn.tag withObject:sss];
                
//                str3 =sun *[[arrprice objectAtIndex:btn.tag] intValue];
                [Count_arr replaceObjectAtIndex:btn.tag withObject:@"1"];
//                NSLog(@"s===%@",arrprice);
                sum = 0;
                for (NSString * str in arrprice) {
                    sum += [str intValue];
                    
                }
                NSLog(@"==sss===%@",arrprice);
                NSLog(@"====%d",sum);
                NSString *sums= [NSString stringWithFormat:@"%d",sum];
                self.allprice.text = sums;

                UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:@"" message:@"亲,购物车的宝贝不能再减少了哦~" delegate:self cancelButtonTitle:nil otherButtonTitles:@"确定", nil];
                [alertView show];
            }
            [table reloadData];
            NSLog(@"s===%@",arrprice);
             NSLog(@"=====%@",Count_arr);
            *stop = YES;
        }
    }];
    
}
-(void)btn2:(UIButton *)btn{

    
    LTableViewCell * cell2 = (LTableViewCell *)[btn superview];
    NSIndexPath *path = [table indexPathForCell:cell2];
//    NSLog(@"---==%ld",(long)[path row]);
    NSMutableDictionary *dic = [contacts objectAtIndex:[path row]];
//    NSLog(@"sss======%@",contacts);
//    NSLog(@"555=====%@",dic);
    if ([[dic objectForKey:@"checked"] isEqualToString:@"NO"]) {
        [[contacts objectAtIndex:[path row]]setObject:@"YES" forKey:@"checked"];
        [cell2 setChecked:YES];
         NSLog(@"========%ld",(long)[path row]);
        
    }else {
        [[contacts objectAtIndex:[path row]]setObject:@"NO" forKey:@"checked"];
        [cell2 setChecked:NO];
       
    }
    if ([[dic objectForKey:@"checked"] isEqualToString:@"YES"]) {
        [button setTitle:@"取消" forState:(UIControlStateNormal)];
    }else{
        [button setTitle:@"全选" forState:(UIControlStateNormal)];
    }
}


- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end

